package com.zjitc.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Properties;
import java.util.concurrent.TimeoutException;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/4/28 13:47
 * @description: 对rabbitmq进行封装
 */
public class RabbitMQ implements MessageQueue {

  private Connection con;
  private static final String QUEUE_NAME = "queue_register_demo";

  public RabbitMQ() {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("47.94.111.174");
    factory.setPort(5672);
    factory.setVirtualHost("/");
    factory.setUsername("guest");
    factory.setPassword("guest");

    try {
      this.con = factory.newConnection();
      Channel channel = this.con.createChannel();
      channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    } catch (Exception ex) {
      throw new ExceptionInInitializerError("初始化rabbit消息队列连接失败\n" + ex.getMessage());
    }
  }

  /**
   * 以特定的RoutingKey，将消息messageBody发送给指定的队列
   */
  @Override
  public void send(String routingKey, String messageBody) {
    if (routingKey == null || routingKey == "") {
      routingKey = QUEUE_NAME;
    }

    Channel channel = null;
    try {
      channel = this.con.createChannel();
      channel.basicPublish("", routingKey, MessageProperties.PERSISTENT_TEXT_PLAIN,
          messageBody.getBytes(Charset.forName("UTF-8")));
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (channel != null) {
        try {
          channel.close();
        } catch (IOException e) {
          e.printStackTrace();
        } catch (TimeoutException e) {
          e.printStackTrace();
        }
      }
    }
  }

  public void close() {
    if (this.con != null) {
      try {
        this.con.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}
